package com.yheriatovych.reductor.example;

import org.pcollections.PStack;

/**
 * 过滤工具
 *
 * @since 2021-05-06
 */
public interface Utils {
    /**
     * 内部接口
     *
     * @param <T>
     * @since 2021-05-06
     */
    interface Predicate<T> {
        boolean call(T value);
    }

    /**
     * 过滤
     *
     * @param xs
     * @param predicate
     * @param <T>
     * @return 过滤后的结果集
     */
    static <T> PStack<T> filter(PStack<T> xs, Predicate<T> predicate) {
        if (xs.isEmpty()) {
            return xs;
        }
        else {
            T head = xs.get(0);
            PStack<T> tail = xs.subList(1);
            if (predicate.call(head)) {
                return filter(tail, predicate).plus(head);
            } else {
                return filter(tail, predicate);
            }
        }
    }
}
